import os
from typing import Dict, List, Any, Optional
import time

class AIAnalyzer:
    """AI分析器，管理多个AI API客户端，优先使用qwen-max，当qwen-max不可用时使用deepseek"""

    def __init__(self):
        """初始化AI分析器"""
        self.qwen_api = None
        self.deepseek_api = None
        self.active_api = None
        self.initialize_apis()

    def initialize_apis(self):
        """初始化所有可用的API客户端"""
        # 尝试初始化Qwen API
        try:
            from modules.qwen_api import QwenAPI
            self.qwen_api = QwenAPI()
            self.active_api = "qwen"
            print("成功初始化Qwen API")
        except Exception as e:
            print(f"初始化Qwen API失败: {str(e)}")
            self.qwen_api = None

        # 如果Qwen API初始化失败，尝试初始化DeepSeek API
        if self.qwen_api is None:
            try:
                from modules.deepseek_api import DeepSeekAPI
                self.deepseek_api = DeepSeekAPI()
                self.active_api = "deepseek"
                print("成功初始化DeepSeek API")
            except Exception as e:
                print(f"初始化DeepSeek API失败: {str(e)}")
                self.deepseek_api = None
                self.active_api = None

        # 如果两个API都初始化失败，抛出异常
        if self.active_api is None:
            raise ValueError("所有API初始化失败，请检查API密钥和网络连接")

    def switch_api(self):
        """切换到备用API"""
        if self.active_api == "qwen" and self.deepseek_api is not None:
            self.active_api = "deepseek"
            print("切换到DeepSeek API")
            return True
        elif self.active_api == "deepseek" and self.qwen_api is not None:
            self.active_api = "qwen"
            print("切换到Qwen API")
            return True
        return False

    def analyze_fundamental_data(self, stock_code: str, stock_name: str, search_results: List[Dict]) -> Dict:
        """分析股票基本面数据

        Args:
            stock_code: 股票代码
            stock_name: 股票名称
            search_results: 搜索结果列表

        Returns:
            分析结果字典
        """
        max_retries = 2
        retry_count = 0

        while retry_count < max_retries:
            try:
                if self.active_api == "qwen" and self.qwen_api is not None:
                    return self.qwen_api.analyze_fundamental_data(stock_code, stock_name, search_results)
                elif self.active_api == "deepseek" and self.deepseek_api is not None:
                    return self.deepseek_api.analyze_fundamental_data(stock_code, stock_name, search_results)
                else:
                    raise ValueError("没有可用的API")
            except Exception as e:
                print(f"使用 {self.active_api} API分析基本面数据失败: {str(e)}")
                if self.switch_api():
                    retry_count += 1
                    continue
                else:
                    raise ValueError(f"所有API都失败，无法分析基本面数据: {str(e)}")

        raise ValueError("达到最大重试次数，无法分析基本面数据")

    def analyze_technical_data(self, stock_code: str, stock_name: str, stock_data: Any) -> Dict:
        """分析股票技术面数据

        Args:
            stock_code: 股票代码
            stock_name: 股票名称
            stock_data: 股票历史数据DataFrame

        Returns:
            分析结果字典
        """
        max_retries = 2
        retry_count = 0

        while retry_count < max_retries:
            try:
                if self.active_api == "qwen" and self.qwen_api is not None:
                    return self.qwen_api.analyze_technical_data(stock_code, stock_name, stock_data)
                elif self.active_api == "deepseek" and self.deepseek_api is not None:
                    return self.deepseek_api.analyze_technical_data(stock_code, stock_name, stock_data)
                else:
                    raise ValueError("没有可用的API")
            except Exception as e:
                print(f"使用 {self.active_api} API分析技术面数据失败: {str(e)}")
                if self.switch_api():
                    retry_count += 1
                    continue
                else:
                    raise ValueError(f"所有API都失败，无法分析技术面数据: {str(e)}")

        raise ValueError("达到最大重试次数，无法分析技术面数据")

    def generate_final_prediction(self, stock_code: str, stock_name: str,
                                 fundamental_analysis: Dict, technical_analysis: Dict) -> Dict:
        """生成最终预测

        Args:
            stock_code: 股票代码
            stock_name: 股票名称
            fundamental_analysis: 基本面分析结果
            technical_analysis: 技术面分析结果

        Returns:
            最终预测结果字典
        """
        max_retries = 2
        retry_count = 0

        while retry_count < max_retries:
            try:
                if self.active_api == "qwen" and self.qwen_api is not None:
                    return self.qwen_api.generate_final_prediction(stock_code, stock_name, fundamental_analysis, technical_analysis)
                elif self.active_api == "deepseek" and self.deepseek_api is not None:
                    return self.deepseek_api.generate_final_prediction(stock_code, stock_name, fundamental_analysis, technical_analysis)
                else:
                    raise ValueError("没有可用的API")
            except Exception as e:
                print(f"使用 {self.active_api} API生成最终预测失败: {str(e)}")
                if self.switch_api():
                    retry_count += 1
                    continue
                else:
                    raise ValueError(f"所有API都失败，无法生成最终预测: {str(e)}")

        raise ValueError("达到最大重试次数，无法生成最终预测")

    def get_active_api_name(self) -> str:
        """获取当前活跃的API名称

        Returns:
            当前活跃的API名称
        """
        return self.active_api
